/*
 * 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.idock.frame.download;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.AsyncTask;
import android.util.Log;
import cn.idock.frame.PzApplication;

/**
 * File download thread
 * 
 * @author idock
 */
public class DownloadTask extends AsyncTask<Void, Integer, Boolean> {

	DownloadJob mJob;

	public DownloadTask(DownloadJob job) {
		mJob = job;
	}

	@Override
	public void onPreExecute() {
		mJob.notifyDownloadStarted();
		super.onPreExecute();
	}

	@Override
	public Boolean doInBackground(Void... params) {
		try {
			return downloadFile(mJob);
		} catch (Exception e) {
			Log.e(PzApplication.TAG, "Download file faild reason-> " + e.getMessage());
			return false;
		}
	}

	@Override
	public void onPostExecute(Boolean result) {
		mJob.notifyDownloadEnded();
		super.onPostExecute(result);
	}

	public static Boolean downloadFile(DownloadJob job) throws IOException {
		// TODO rewrite to apache client
		Log.i("TAG", "downloadFile:" + job);
		String mDestination = job.getDestination();
		String url = job.getUrl();

		URL u = new URL(url);
		HttpURLConnection c = (HttpURLConnection) u.openConnection();
		c.setRequestMethod("GET");
		c.setDoOutput(true);
		c.connect();
		job.setTotalSize(c.getContentLength());

		Log.i(PzApplication.TAG, "creating file");

		String path = DownloadHelper.getAbsolutePath(url, mDestination);
		String fileName = DownloadHelper.getFileName(url);

		try {
			// Create multiple directory
			boolean success = (new File(path)).mkdirs();
			if (success) {
				Log.i(PzApplication.TAG, "Directory: " + path + " created");
			}

		} catch (Exception e) {// Catch exception if any
			Log.e(PzApplication.TAG, "Error creating folder", e);
			return false;
		}

		FileOutputStream f = new FileOutputStream(new File(path, fileName));

		InputStream in = c.getInputStream();

		if (in == null) {
			// When InputStream is a NULL
			f.close();
			return false;
		}

		byte[] buffer = new byte[1024];
		int lenght = 0;
		while ((lenght = in.read(buffer)) > 0) {
			f.write(buffer, 0, lenght);
			job.setDownloadedSize(job.getDownloadedSize() + lenght);
		}

		f.close();

		return true;

	}
}
